package com.cate.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.cate.base.BasePageVO;
import com.cate.exception.BusinessException;
import com.cate.mapper.CategoryMapper;
import com.cate.pojo.dto.CategoryInfoDTO;
import com.cate.pojo.dto.CategoryPageDTO;
import com.cate.pojo.entity.Category;
import com.cate.result.SystemCode;
import com.cate.service.CategoryService;
import com.cate.utils.PageUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Min;
import java.util.List;

/**
 * @CreateTime: 2023/7/29
 * @Author: <==lhd==>
 * @Description: 分类管理
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void update(CategoryInfoDTO categoryInfoDTO) {
        Category category = BeanUtil.copyProperties(categoryInfoDTO, Category.class);
        final int i = categoryMapper.update(category);
        if (i <= 0) {
            throw new BusinessException(SystemCode.PARAMETER_VALID_ERROR, "分类更新失败");
        }
    }

    @Override
    public BasePageVO<Category> pageQuery(CategoryPageDTO categoryPageDTO) {
        PageHelper.startPage(categoryPageDTO.getPage(), categoryPageDTO.getPageSize());
        final Page<Category> categoryPage = categoryMapper.selectPage(categoryPageDTO.getName(), categoryPageDTO.getType());
        return PageUtil.getPageResult(categoryPage);
    }

    @Override
    public void setStatus(Long categoryId, Integer status) {
        Category category = new Category();
        category.setStatus(status);
        category.setId(categoryId);
        final int i = categoryMapper.update(category);
        if (i <= 0) {
            throw new BusinessException(SystemCode.PARAMETER_VALID_ERROR, "更新失败");
        }
    }

    @Override
    public void save(CategoryInfoDTO categoryInfoDTO) {
        Category category = BeanUtil.copyProperties(categoryInfoDTO, Category.class);
        category.setStatus(1);
        final int i = categoryMapper.insert(category);
        if (i <= 0) {
            throw new BusinessException(SystemCode.PARAMETER_VALID_ERROR, "保存失败");
        }
    }

    @Override
    public void deleteById(Long categoryId) {
        final int i = categoryMapper.deleteById(categoryId);
        if (i <= 0) {
            throw new BusinessException(SystemCode.PARAMETER_VALID_ERROR, "删除失败");
        }
    }

    @Override
    public List<Category> listByType( Integer type) {
        final List<Category> list = categoryMapper.selectList(type);
        if (list.isEmpty()) {
            throw new BusinessException(SystemCode.PARAMETER_VALID_ERROR, "查询失败");
        }
        return list;
    }
}
